// -----------------------------------------------------------------------------
// DM 是 .NET 5 平台下开发管理的系统。
// Copyright © 2021 DM, 虫儿飞科技 Co.,Ltd.
//
// 框架名称：Furion
// 框架版本：1.0.0
// -----------------------------------------------------------------------------

using Abc.Application;
using Abc.Core;

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using System.Linq;
using System.Threading.Tasks;

using Tool;

namespace Abc.Web.Mvc.Areas.HtAdmin.Controllers
{
    //[AllowAnonymous]
    [Area("HtAdmin")]
    public class AccountController : Controller
    {
        private readonly IUserService _userService;
        private readonly IDataConfigService _dataConfigService;
        private readonly IHttpContextAccessor httpContextAccessor;

        public AccountController(IUserService userService
            , IDataConfigService dataConfigService
            , IHttpContextAccessor httpContextAccessor)
        {
            _userService = userService;
            _dataConfigService = dataConfigService;

            this.httpContextAccessor = httpContextAccessor;
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<ActionResult> Login(string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;

            var dataconfig = await _dataConfigService.GetByKey("CopyrightInformation");

            ViewData["CopyrightInformation"] = dataconfig?.Value ?? "";
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> LoginAsync(UserLoginInput logininput, string VerifyCode)
        {
            if (!WebHelper.VerifyCode(httpContextAccessor, VerifyCode, verifyKey: "HtAdmin"))
            {
                return Json(new ResultData<string> { Succeeded = false, Errors = "验证码不正确" });
            }

            var resultdata = await _userService.Login(logininput);

            return Json(resultdata);
        }

        [AllowAnonymous]
        //public async Task<IActionResult> LoginOut()
        //{
        //    await HttpContext.SignOutAsync(AuthorizeKey.AdminAuthenticationScheme);
        //    return RedirectToAction("Login", "Account", new { area = "HtAdmin" });
        //}
        public async Task<JsonResult> LoginOut()
        {
            await HttpContext.SignOutAsync(AuthorizeType.AdminAuthenticationScheme);
            //  return RedirectToAction("Login", "Account", new { area = "HtAdmin" });
            return Json(new ResultData<string>(succeeded: true));
        }

        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetVerifyCode()
        {
            var imgbyte = WebHelper.GetVerifyCode(httpContextAccessor, verifyKey: "HtAdmin");
            return File(imgbyte.ToArray(), @"image/png");
        }
    }
}